package com.spsoft.vatoutinv.util.xml;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.XML;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.BusinessException;
import com.spsoft.vatoutinv.util.xml.entity.XMLEntity;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;

/**
 * @author wangy
 * @date 2023/12/25 9:30
 */
public class XmlInvoiceUtils {

    /**
     * 生成xml文件
     *
     * @param entity  实体类
     * @param outPath 文件输出路径
     * @return 文件输出路径
     */
    public static String genEInvoice(XMLEntity entity, String outPath) {
        String xmlTitle = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n";
        JSONObject jsonObject = JSONUtil.parseObj(entity);
        String toXml = XML.toXml(jsonObject);
        // "<[^/>]*?/>" 匹配自闭合标签
        toXml = toXml.replaceAll("<[^/>]*?/>", "");
        // 把 TotalTaxIncludedAmount 转成 TotalTax-includedAmount
        toXml = toXml.replace("TotalTaxIncludedAmount", "TotalTax-includedAmount");
        // 把 TotalTaxIncludedAmountInChinese 转成 TotalTax-includedAmountInChinese
        toXml = toXml.replace("TotalTaxIncludedAmountInChinese", "TotalTax-includedAmountInChinese");
        // 格式化XML
        toXml = prettyXML(toXml, 4);
        FileUtil.writeString(xmlTitle + toXml, outPath, "UTF-8");

        return outPath;
    }

    /**
     * 格式化xml
     *
     * @param xmlString xml内容
     * @param indent    缩进多少空格
     * @return 格式化后的xml
     */
    public static String prettyXML(String xmlString, int indent) {
        // 格式化XML
        XmlOptions options = new XmlOptions();
        options.setSavePrettyPrint();
        options.setSavePrettyPrintIndent(indent);
        try {
            xmlString = XmlObject.Factory.parse(xmlString).xmlText(options);
        } catch (XmlException e) {
            throw new BusinessException(ResponseEnum.XML_PRETTY_ERROR);
        }
        return xmlString;
    }

}
